package com.jiantong.web.controller.cloud;

import com.google.common.base.Throwables;
import com.google.common.collect.Sets;
import com.jiantong.web.core.cloud.config.AliyunToken;
import com.jiantong.web.core.cloud.service.impl.AliyunFileServer;
import io.terminus.common.model.Response;
import io.terminus.pampas.openplatform.annotations.OpenMethod;
import io.terminus.pampas.openplatform.exceptions.OPServerException;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Set;
import java.util.UUID;

/**
 * Created by niufei on 2017/5/5.
 *
 */
@RestController
@Slf4j
public class FileUpload {
    private static final int IMAGE = 0;

    private static final int VIDEO = 1;

    private static final int VIDEO_IMAGE = 2;

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern("yyyy/MM/dd");

    private static final Set<String> IMAGE_ALLOW_EXT = Sets.newHashSet(
            "jpg", "png", "gif" // 图片格式
    );

    private static final Set<String> VIDEO_ALLOW_EXT = Sets.newHashSet(
            "avi", "3gp", "mp4" // 视频格式
    );

    @Autowired
    private AliyunFileServer aliyunFileServer;

    @Autowired
    private AliyunToken aliyunToken;


    @PostMapping(value = "/api/upload/image")
    public String uploadImage(@RequestBody MultipartFile image) {
        try {
            String imageExt = getExtName(image);
            checkImageExt(imageExt);
            String path = generateSavePath(imageExt , IMAGE);
            path = aliyunFileServer.write(path,image);
            return Response.ok(aliyunToken.getBaseUrl() + "/" + path).getResult();
        } catch (Exception e) {
            log.error("upload image failed",e.getMessage());
            throw new OPServerException("upload image failed");
        }
    }

    @PostMapping(value = "/api/upload/video")
    public String uploadVideo(@RequestBody MultipartFile video){
        try {
            String videoExt = getExtName(video);
            checkVideoExt(videoExt);
            String path = generateSavePath(videoExt ,VIDEO);
            path = aliyunFileServer.write(path,video);
            return Response.ok(aliyunToken.getBaseUrl() + "/" + path).getResult();
        } catch (Exception e) {
            log.error("upload video failed",e.getMessage());
            throw new OPServerException("upload video failed");
        }
    }

    @PostMapping(value = "/api/upload/video/imge")
    public String uploadVideoImage(@RequestBody MultipartFile videoImage){
        try {
            String videoImageExt = getExtName(videoImage);
            //checkImageExt(videoImageExt);
            String path = generateSavePath(videoImageExt ,VIDEO_IMAGE);
            path = aliyunFileServer.write(path,videoImage);
            return Response.ok(aliyunToken.getBaseUrl() + "/" + path).getResult();
        } catch (Exception e) {
            log.error("upload videoImage failed",e.getMessage());
            throw new OPServerException("upload videoImage failed");
        }
    }

    @DeleteMapping(value = "/api/delete/file")
    public boolean deleteFile(String path){
        try{
            return aliyunFileServer.delete(path);
        }catch (Exception e){
            log.error("failed to delete {} from oss, cause:{}", path, Throwables.getStackTraceAsString(e));
            return false;
        }
    }

    /**
     * 获取去文件扩展名
     * @param file 文件
     * @return 文件扩展名
     */
    private String getExtName(MultipartFile file){
        String fullName = file.getOriginalFilename().toLowerCase();
        String fileName = new File(fullName).getName();
        int dotIndex = fileName.lastIndexOf(".");
        return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
    }

    /**
     * 检查文件扩展名
     * @param ext 文件扩展名
     */
    private void checkImageExt(String ext){
        if (!IMAGE_ALLOW_EXT.contains(ext)) {
            throw new RuntimeException("FileDao.ext.is.not.allowed");
        }
    }

    /**
     * 检查文件扩展名
     * @param ext 文件扩展名
     */
    private void checkVideoExt(String ext){
        if (!VIDEO_ALLOW_EXT.contains(ext)) {
            throw new RuntimeException("FileDao.ext.is.not.allowed");
        }
    }

    /**
     * 生成保存的文件路径
     *
     * @param ext 扩展名
     * @param type 文件类型
     * @return 文件路径
     */
    private  String generateSavePath(String ext ,int type) {
        String prefix = null;
        switch (type){
            case IMAGE:
                prefix = "IMAGE";
                break;
            case VIDEO:
                prefix = "VIDEO";
                break;
            case VIDEO_IMAGE :
                prefix = "VIDEO_IMAGE";
                break;
            default:
                break;
        }
        return prefix + DateTime.now().toString(DATE_FORMATTER) + "/" + UUID.randomUUID().toString() + "." + ext;
    }
}
